function [selection,trialtype] = emotion_files(filenames_happy,filenames_neutral,n_trials)
%   [selection,match] = sternberg_files(filenames,ntrials)
%       Picks at random ntrials groups of filenames

% Keep a persistent index of previously used images
persistent already_used_happy already_used_neutral;
n_filenames_neutral=length(filenames_neutral);
n_filenames_happy=length(filenames_happy);
usable_neutral =1:n_filenames_neutral;
usable_happy =1:n_filenames_happy;
% Exclude images that have been previously used
usable_neutral(already_used_neutral) = [];
usable_happy(already_used_happy) = [];
n_usable_neutral=length(usable_neutral);
n_usable_happy=length(usable_happy);

% Half of trails are happy (vs neutral)
trialtype = zeros(1,n_trials);
n_neutral = ceil(n_trials/2);
n_happy = n_trials-n_neutral;

trialtype = [ repmat(0,1,n_neutral) repmat(1,1,n_happy)];
% Finally we permute trial order
trialtype = trialtype(randperm(n_neutral+n_happy));
% And make sure we do not have bizarre series:
bad=1;
% while bad
%     bad = any(all([...
%         diff(trialtype(1:end-2));...
%         diff(trialtype(2:end-1));...
%         diff(trialtype(3:end  ))]==0,1));
% end
fprintf('Emotion Trial types: %s\n',sprintf('%d ', trialtype));

% Now get the images:
sel_happy = randperm(n_usable_happy);
sel_happy = sel_happy(1:n_happy);

sel_neutral = randperm(n_usable_neutral);
sel_neutral = sel_neutral(1:n_neutral);

selection(trialtype==0) = filenames_neutral(sel_neutral);
selection(trialtype==1) = filenames_happy(sel_happy);

already_used_neutral = [already_used_neutral sel_neutral];
already_used_happy   = [already_used_happy   sel_happy];
